// pages/shoppingCart/shoppingCart.js
/**
 * 前端控制全选，和非全选，有部分问题存在,个人测试版小程序无法接入支付
 */
import {findPageCarts,deleteCarts,updateCartCheck,addOrEdit,addCacheCart} from '@/api/cart'
import {userBehaviors} from '@/behaviors/userBehaviors'
import {msgTip, msgTipAlert} from '@/utils/MsgTipApi'
Page({

  behaviors:[userBehaviors],
  /**
   * 页面的初始数据
   */
  data: {
    selectAll:false,
    selectCount:0,
    totalPrice:0,
    resData:[],
    total:0,
    isAll:false,
    isLoading: false,
    reqData:{
      pageIndex:1,
      pageSize:20,
      userId: null
    }
  },

  /**
   * 初始化查询参数
   */
  clearData(){
    this.setData({
      resData:[],
      total:0,
      selectCount:0,
      totalPrice:0,
      selectAll:false,
      actionShow:false,
      // 根据ID查询购物车的数据
      cartData:{},
      "reqData.pageIndex":1,
      "reqData.pageSize":20,
      "reqData.userId":null
    })
  },

  /**
   * 进行分页查询 
   */
  async findPageCarts(){
    this.data.isLoading = true
    let data = await findPageCarts(this.data.reqData);
    let totalPrice = 0;
    let selectAll = true;
    data.records.forEach(item =>{
      if(item.isCheck){
        totalPrice += item.goodPrice * item.count * 100;
        this.data.selectCount++;
      }
    })
    data.records.filter(item =>{
      if(!item.isCheck){
        selectAll = false;
        return;
      }
    })
  
    this.setData({
      resData:[...this.data.resData, ...data.records],
      total:data.total,
      totalPrice,
      selectAll
    })
    this.data.isLoading = false
    if(this.data.resData.length == this.data.total){
      this.setData({isAll:true})
    }else{
      this.setData({isAll:false})
    }
  },
  // 更新选中状态
  updateCheck(event){
    let {index} = event.currentTarget.dataset;
    // 更新选中状态
    let {isCheck,id} = this.data.resData[index];
   
    this.setData({
      [`resData[${index}].isCheck`]:  !isCheck,
      totalPrice: 
       !isCheck == false ? this.data.totalPrice - this.data.resData[index].goodPrice * this.data.resData[index].count * 100 : this.data.resData[index].goodPrice * this.data.resData[index].count * 100 + this.data.totalPrice,
      selectCount:  !isCheck == true ? this.data.selectCount + 1 : this.data.selectCount - 1,
    })
    this.data.selectCount >= this.data.resData.length ? this.setData({
      selectAll: true
    }) : this.setData({
      selectAll: false
    })
    let params = {id,isCheck: !isCheck}
    updateCartCheck(params)
  },
  // 更新选中当前数据中的全部
  selectAllCart(){
    this.setData({
      selectAll: !this.data.selectAll,
      totalPrice:0
    })
    this.data.selectAll ? 
    this.data.resData.forEach((item,index) =>{
      this.setData({
        [`resData[${index}].isCheck`]:  true,
        totalPrice: this.data.resData[index].goodPrice * this.data.resData[index].count * 100 + this.data.totalPrice,
        selectCount:  this.data.resData.length,
      })
    })
    : this.data.resData.forEach((item,index) =>{
      this.setData({
        [`resData[${index}].isCheck`]:  false,
        totalPrice: 0,
        selectCount:  0,
      })
    })
    let params = {isAll: true, isAllChecked: this.data.selectAll}
    updateCartCheck(params)
  },
  // 删除购物车中的数据
  async delCartItem(event){
    let {id,index} = event.currentTarget.dataset;
    let flag = await msgTipAlert({title:'警告',content:'将删除该商品信息'})
    if(flag){
      let res = await deleteCarts(id)
      this.clearData()
      this.findPageCarts()
    }
  },
  // 编辑购物车
  async editCart(event){
    let count = event.detail;
    let {id,index,goodid} = event.currentTarget.dataset;
    let curData = this.data.resData[index];
    // 获取差值，用来计算总价
    let divied = count - curData.count;
    let params = {id,count:divied,goodId:goodid}
    this.setData({isLoading:true})
    await addOrEdit(params)
    this.setData({isLoading:false})
    this.setData({
      totalPrice: this.data.totalPrice > 0 ? this.data.totalPrice + divied * curData.goodPrice * 100 : 0,
      [`resData[${index}].count`]:count
    })
  },
  // 购物车提交
  async onsubmitCart(event){
    if(this.data.totalPrice <= 0){
      msgTip({title:'请先选择购买商品'})
      return;
    }
    // 将这个数据传递给redis暂存，15分钟内未支付，自动取消
    let ids = []
    this.data.resData.forEach(item=>{
      if(item.isCheck) ids.push(item.id)
    })
    let data = await addCacheCart(ids)
    if(data == 200){
      wx.navigateTo({
        url: '/modules/orderModules/pages/orderSubmit/index',
      })
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(!this.data.token) return
    this.findPageCarts()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.clearData()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.clearData()
    this.findPageCarts()
    // 前端控制全选的原因，需要将数据清除一遍
    this.setData({
      selectCount: 0,
      selectAll:false,
      totalPrice:0
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 如果正在请求或者已经加载完毕，那么就直接返回
    if(this.data.isLoading || this.data.isAll) return
    // 否则页码加1，继续请求
    this.setData({
      "reqData.pageIndex": this.data.reqData.pageIndex  + 1
    })
    this.findPageCarts()
    if(this.data.resData.length > this.data.selectCount){
      this.setData({
        selectAll:false
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})